<template>
  <!-- 英雄部分 - Hero Section (浅红加白配色) -->
  <div class="w-full bg-white relative overflow-hidden mt-16 mb-8">
    <!-- 背景图案装饰 -->
    <div class="absolute inset-0 overflow-hidden">
      <div class="absolute top-0 left-0 w-full h-full bg-gradient-to-br from-white via-[#FFF5F5] to-[#FFEBEB] opacity-80"></div>
      <div class="absolute -right-20 -top-20 w-80 h-80 bg-[#F05454]/5 rounded-full blur-3xl"></div>
      <div class="absolute -left-40 -bottom-40 w-[400px] h-[400px] bg-[#F05454]/5 rounded-full blur-3xl"></div>
      <div class="absolute right-1/3 top-1/4 w-48 h-48 bg-[#F05454]/5 rounded-full blur-2xl"></div>
    </div>

    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-14 md:py-16 lg:py-20 relative z-10">
      <!-- 顶部装饰线条 -->
      <div class="w-20 h-1 bg-[#F05454] mb-10 md:mb-12"></div>

      <div class="flex flex-col md:flex-row items-start justify-between gap-16 lg:gap-20">
        <!-- 左侧文本内容与交互选项 -->
        <div class="w-full md:w-2/5 text-[#333333] space-y-6">
          <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold leading-tight tracking-tight mb-8">
            {{ heroSection?.main_title }}<span class="text-[#F05454] border-b-4 border-[#F05454] pb-1">{{ heroSection?.highlight_text }}</span>
            <br class="hidden md:block">{{ heroSection?.sub_title }}
          </h2>

          <!-- 交互选项 -->
          <div class="flex flex-col space-y-4">

            <div v-for="(option, index) in heroOptions" :key="option.id"
                 @mouseover="activeImage = index"
                 @click="handleOptionClick(option)"
                 @click.stop="console.log('点击事件触发:', option.title)"
                 class="px-4 py-3 rounded-md cursor-pointer transition-all duration-300 hover:bg-[#F05454]/10 hover:text-[#F05454] border border-transparent hover:border-[#F05454]/20 relative z-50"
                 :class="{'bg-[#F05454]/10 text-[#F05454] border-[#F05454]/20': activeImage === index}"
                 style="pointer-events: auto;"
                 title="点击跳转到对应页面">
              <div class="flex items-center">
                <div class="w-2 h-2 bg-[#F05454] rounded-full mr-3" :class="{'opacity-100': activeImage === index, 'opacity-0': activeImage !== index}"></div>
                <div class="font-medium text-lg">{{ option.title }}</div>
              </div>
              <div class="text-sm text-[#666666] mt-2 ml-5">{{ option.description }}</div>
            </div>
          </div>

          <div class="pt-4 flex flex-wrap gap-4">
            <a :href="heroSection?.button1_link" class="inline-block px-8 py-3 bg-[#F05454] text-white font-semibold hover:bg-[#E04040] transform hover:-translate-y-1 transition-all duration-300 group relative overflow-hidden">
              <span class="relative z-10">{{ heroSection?.button1_text }}</span>
              <span class="absolute inset-0 bg-[#E04040] transform translate-y-full group-hover:translate-y-0 transition-transform duration-300"></span>
            </a>
            <a :href="heroSection?.button2_link" class="inline-block px-8 py-3 bg-transparent border border-[#F05454] text-[#F05454] font-semibold hover:bg-[#F05454]/5 transform hover:-translate-y-1 transition-all duration-300">
              {{ heroSection?.button2_text }}
            </a>
          </div>
        </div>

        <!-- 右侧图片/图形 (交互切换版) -->
        <div class="w-full md:w-1/2 flex justify-end">
          <div class="relative w-full max-w-lg">
            <!-- 交互切换图片 -->
            <div class="relative z-10 overflow-hidden rounded-md shadow-lg">
              <!-- 动态图片切换 -->
              <div v-for="(option, index) in heroOptions" :key="option.id" v-show="activeImage === index" class="relative overflow-hidden transition-all duration-500 ease-out aspect-square">
                <img 
                  :src="option.image_url" 
                  :alt="option.title" 
                  class="w-full h-full object-cover transition-all duration-700 ease-out" 
                  :class="{'scale-105': activeImage === index}"
                  @error="handleImageError(option, index)"
                >
                <div v-if="!option.image_url" class="absolute inset-0 bg-gray-200 flex items-center justify-center">
                  <span class="text-gray-500">图片加载失败: {{ option.title }}</span>
                </div>
                <div class="absolute inset-0 bg-gradient-to-t from-[#F05454]/60 to-transparent opacity-40"></div>
                <div class="absolute bottom-0 left-0 p-6 text-white">
                  <div class="text-xl font-semibold mb-2">{{ option.title }}</div>
                  <div class="w-10 h-0.5 bg-white"></div>
                </div>
              </div>
            </div>

            <!-- 装饰元素 -->
            <div class="absolute -bottom-4 -right-4 w-full h-full border-2 border-[#F05454] -z-10 transform translate-x-4 translate-y-4 rounded-md"></div>
            <div class="absolute -top-4 -left-4 w-32 h-32 bg-[#F05454]/10 -z-10"></div>
          </div>
        </div>
      </div>

      <!-- 底部特色数据 -->
      <div class="mt-16 grid grid-cols-2 md:grid-cols-4 gap-6 md:gap-4 lg:gap-6">
        <div v-for="stat in heroStats" :key="stat.id" class="border-t border-[#F05454]/20 pt-4">
          <div class="text-3xl md:text-4xl font-bold mb-1 text-[#333333]">
            {{ stat.number }}<span class="text-[#F05454]">{{ stat.suffix }}</span>
          </div>
          <div class="text-xs text-[#777777] uppercase tracking-wider">{{ stat.label }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { homeApi } from '@/utils/api';

// Vue Router实例
const router = useRouter();

// 定义emit
const emit = defineEmits(['api-error'])

// 英雄区域数据
const heroSection = ref(null);
const heroOptions = ref([]);
const heroStats = ref([]);

// 当前激活的图片索引（用于英雄部分的交互）
const activeImage = ref(0);

const error = ref({
  heroSection: null,
  heroOptions: null,
  heroStats: null
});

  // 获取英雄区域数据
  const fetchHeroSection = async () => {
    error.value.heroSection = null;
    try {
      console.log('正在请求英雄区域数据...');
      const response = await homeApi.getHeroSectionData();
      heroSection.value = response.data || {};
      // 如果没有数据，使用默认值
      if (!heroSection.value.main_title) {
        console.warn('英雄区域数据不完整，使用默认值');
        heroSection.value = {
          main_title: '欢迎来到',
          highlight_text: '南洋理工大学',
          sub_title: '探索无限可能',
          button1_text: '了解更多',
          button1_link: '/about',
          button2_text: '联系我们',
          button2_link: '/contact'
        };
      }
    } catch (err) {
      console.error('获取英雄区域数据失败:', err);
      console.error('请求URL:', err.config?.url);
      console.error('响应状态:', err.response?.status);
      console.error('响应数据:', err.response?.data);
      // 触发API错误事件，让父组件处理
      emit('api-error', err);
    }
  };

  // 获取英雄选项数据
  const fetchHeroOptions = async () => {
    error.value.heroOptions = null;
    try {
      console.log('正在请求英雄选项数据...');
      const response = await homeApi.getHeroOptions();
      console.log('英雄选项API响应:', response);
      // 临时添加调试日志，显示每个选项的图片URL
      if (response.data && Array.isArray(response.data)) {
        response.data.forEach((option, index) => {
          console.log(`选项${index}: ${option.title}`, `图片URL: ${option.image_url}`);
        });
      }
      heroOptions.value = response.data || [];

      // 如果没有数据，显示错误信息
      if (heroOptions.value.length === 0) {
        console.warn('英雄选项数据为空');
        error.value.heroOptions = '暂无英雄选项数据';
        heroOptions.value = [];
      }
    } catch (err) {
      console.error('获取英雄选项数据失败:', err);
      console.error('请求URL:', err.config?.url);
      console.error('响应状态:', err.response?.status);
      console.error('响应数据:', err.response?.data);
      // 触发API错误事件，让父组件处理
      emit('api-error', err);
    }
  };

  // 获取英雄统计数据
  const fetchHeroStats = async () => {
    error.value.heroStats = null;
    try {
      console.log('正在请求英雄统计数据...');
      const response = await homeApi.getHeroStats();
      console.log('英雄统计API响应:', response);
      heroStats.value = response;
      // 如果没有数据，显示错误信息
      if (heroStats.value.length === 0) {
        console.warn('英雄统计数据为空');
        error.value.heroStats = '暂无统计数据';
        heroStats.value = [];
      }
    } catch (err) {
      console.error('获取英雄统计数据失败:', err);
      console.error('请求URL:', err.config?.url);
      console.error('响应状态:', err.response?.status);
      console.error('响应数据:', err.response?.data);
      // 触发API错误事件，让父组件处理
      emit('api-error', err);
    }
  };

// 处理选项点击事件
const handleOptionClick = (option) => {
  console.log('点击选项:', option.title);

  // 根据选项标题跳转到对应页面
  switch (option.title) {
    case '学校荣誉':
      router.push({ name: 'SchoolHonors' });
      break;
    case '标志成果':
      router.push({ name: 'SignificantAchievements' });
      break;
    case '组织架构':
      router.push({ name: 'OrganizationStructure' });
      break;
    default:
      // 如果有链接URL，则跳转到该链接
      if (option.link_url) {
        if (option.link_url.startsWith('http')) {
          // 外部链接
          window.open(option.link_url, '_blank');
        } else {
          // 内部路由
          router.push(option.link_url);
        }
      } else {
        console.log('未知选项:', option.title);
      }
  }
};

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 不预设默认数据，直接从API获取
    heroSection.value = null;
    heroOptions.value = [];
    heroStats.value = [];

    // 尝试从 API 获取数据
    await Promise.all([
      fetchHeroSection(),
      fetchHeroOptions(),
      fetchHeroStats()
    ]);
  } catch (error) {
    console.error('Error in onMounted:', error);
  }
});
</script>

<style scoped>
/* 其他样式 */
</style>
